#include <asm-generic/errno-base.h>
#include <errno.h>
#include <fcntl.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>

int main(int argc, char *argv[]) {

  sem_t *sem[2];
  sem[0] = sem_open("a", O_CREAT, 0666, 1);
  sem[1] = sem_open("b", O_CREAT, 0666, 0);

  key_t key = ftok(".", 1);
  if (key < 0) {
    perror("ftok fail");
    exit(-1);
  }

  int shm_id = shmget(key, 1024, IPC_CREAT | IPC_EXCL | 0666);
  if (shm_id < 0) {
    if (errno == EEXIST) {
      shm_id = shmget(key, 1024, 0666);
    } else {
      perror("shmget fail");
      exit(-1);
    }
  } 
  char* shm_buf = shmat(shm_id,NULL,0);
  if(shm_buf == (void*)-1){
    perror("shmdt fail");
    exit(-1);
  }

  while(1){
    printf("please input:");
    sem_wait(sem[0]);
    scanf("%s",shm_buf);
    sem_post(sem[1]);
    if(!(strcmp("bye",shm_buf)))
      break;
  }

  sem_close(sem[0]);
  sem_close(sem[1]);
  sem_unlink("a");
  sem_unlink("b");
  return 0;
}
